package cn.i7baozh.boot.learn.dync;

import cn.i7baozh.boot.learn.initializer.config.MyConfig;
import cn.i7baozh.boot.learn.initializer.processor.ConfigChangeDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * @author zhangbaoqi532
 * @date 2025/1/14
 */
@Slf4j
@RestController
public class DynamicValueTest implements CommandLineRunner {

    @Value("${dynamic.value:代码默认值}")
    private String dynamicValue;

    /**
     * http://localhost:8989/configValue
     * @return
     */
    @GetMapping("/get")
    public String configValue(@Value("${dynamic.value:controller的值}") String dyncVal){
        log.info("controller的值 {}", dyncVal);

        log.info("@value的值 {}", dynamicValue);
        log.info("config获取的值 {}", MyConfig.getProperty("dynamic.value"));
        return "ok";
    }

    /**
     * http://localhost:8989/configValue
     * @return
     */
    @GetMapping("/get1")
    public String get1(){
        log.info("config获取的值 {}", MyConfig.getProperty("third.xxConfig"));
        return "ok";
    }
    @GetMapping("/get2")
    public String get2(){
        log.info("config获取的值 {}", MyConfig.getProperty("third.xxConfig2"));
        return "ok";
    }

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    /**
     * http://localhost:8989/update?type=1&configValue=remoteValueXX
     * @return
     */
    @GetMapping("/update")
    public String update() {
        String configKey = "dynamic.value";
        ConfigChangeDTO configChangeDTO = new ConfigChangeDTO(configKey
                ,"代码改变的值" + UUID.randomUUID());
        applicationEventPublisher.publishEvent(configChangeDTO);
        return "ok";
    }

    @Override
    public void run(String... args) throws Exception {
        log.info("********** 启动时获取到的值:{}", MyConfig.getProperty("dynamic.value"));
    }
}
